<template>
  <!-- 添加/编辑  字段弹窗 -->
  <HModal :model-value="isOpen" width="500" @close="onClose">
    <template #header>
      <h3>{{ title }}</h3>
    </template>
    <div v-loading="loading">
      <el-form
       label-width="100"
        ref="formRef"
        :rules="rules"
        :model="networkFieldVo"
        @validate="handleFormValidate"
        class="modal_form_content"
      >
        <!-- 字段名称 -->
        <el-form-item
          label="字段名称"
          class="form_input_item"
          :class="{ error_form_item: !formValidateResult['name'] }"
          prop="name"
        >
          <el-input
            maxlength="20"
            v-model="networkFieldVo.name"
            clearable
            placeholder="请输入名称"
          />
        </el-form-item>

        <!-- 字段类型 -->
        <el-form-item label="字段类型" class="form_input_item" prop="type">
          <el-select v-model="networkFieldVo.type" :disabled="networkFieldVo.id !== ''">
            <el-option
              v-for="item in type == 0 ? fieldOption0 : fieldOption1"
              :key="item.value"
              :value="item.value"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <!-- 提示信息 -->
        <el-form-item label="提示信息">
          <el-input
            maxlength="30"
            v-model="networkFieldVo.tip"
            clearable
            placeholder="请输入提示信息"
          />
        </el-form-item>
     <!-- 字段状态 -->
     <el-form-item label="字段状态" class="form_radio_group_item" prop="status">
          <el-radio-group v-model="networkFieldVo.status">
            <el-radio :value="false">
              <span class="bg_text">启用</span>
            </el-radio>
            <el-radio :value="true">
              <span class="bg_text">禁用</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 字段选项 -->
        <el-form-item label="是否必填" class="form_radio_group_item" prop="required">
          <el-radio-group v-model="networkFieldVo.required">
            <el-radio :value="true">
              <span class="bg_text">必填</span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">可填</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

     
      <!-- 移动显示 -->
      <el-form-item label="移动端显示" class="form_radio_group_item" prop="mobileShow">
          <el-radio-group v-model="networkFieldVo.mobileShow">
            <el-radio :value="true">
              <span class="bg_text">显示</span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">不显示</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 单选/多选的字段内容 -->
        <span v-if="networkFieldVo.type == 3 || networkFieldVo.type == 4">
          <el-form-item :required="true" label="字段内容" class="form_height_22_item">
            <HPlainButton :padding-lr="6" :height="22" @click="addFieldContent"
              >+ 新增
            </HPlainButton>
          </el-form-item>
          <div class="list">
            <template v-for="(item, index) in networkFieldVo.contentVos" :key="index">
              <el-form-item
                class="form_input_item"
                :prop="`contentVos[${index}][val]`"
                :rules="rules.val"
                :label="`${index + 1}、`"
                :required="false"
              >
                <div style="display: flex; align-items: center; width: 100%; gap: 5px">
                  <el-input
                    v-model="item.val"
                    class="text-input"
                    clearable
                    placeholder="请输入字段内容"
                    maxlength="20"
                  />
                  <div style="width: 24px; height: 28px; line-height: 28px">
                    <HLink type="error" @click="handleDele(index, item)">删除</HLink>
                  </div>
                </div>
              </el-form-item>
            </template>
          </div>
        </span>
        <span
          v-if="networkFieldVo.type == 5 || networkFieldVo.type == 6 || networkFieldVo.type == 7"
        >
          <!-- 最大尺寸(MB) -->
          <el-form-item label="最大尺寸(MB)" prop="uploadSize" class="form_input_item">
            <el-input
              v-model="networkFieldVo.uploadSize"
              @input="limitNum(networkFieldVo.uploadSize, 100)"
              type="number"
              @change="networkFieldVo.uploadSize ? '' : (networkFieldVo.uploadSize = 1)"
              clearable
              placeholder="请输入尺寸"
            />
          </el-form-item>

          <!-- 上传数量 -->
          <el-form-item label="上传数量" class="form_input_item margin_top_12" prop="uploadQty">
            <el-input
              v-model="networkFieldVo.uploadQty"
              @input="limitNum(networkFieldVo.uploadQty, 10)"
              type="number"
              @change="networkFieldVo.uploadQty ? '' : (networkFieldVo.uploadQty = 1)"
              clearable
              placeholder="请输入数量"
            />
          </el-form-item>
        </span>
      </el-form>
    </div>

    <template #footerLeft>
      <HPlainBgButton
        is-modal
        type="error"
        @focus="(e: Event) => (e.target as HTMLButtonElement).blur()"
        v-show="networkFieldVo.id"
        @click="onDelNetworkField(networkFieldVo)"
        >删除</HPlainBgButton
      >
    </template>

    <template #footerRight>
      <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </HModal>
</template>

<script setup lang="ts">
  import { ref, reactive, markRaw, watch, toRefs } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Delete } from '@element-plus/icons-vue'
  import _ from 'lodash'
  import HPlainButton from '../common/button/HPlainButton.vue'
  import HButton from '../common/button/HButton.vue'
  import HPlainBgButton from '../common/button/HPlainBgButton.vue'
  import HModal from '../common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'
  import HLink from '../common/link/HLink.vue'

  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService([
      { name: 'name', isSelect: false },
      { name: 'val', isSelect: false },
      { name: 'required', isSelect: true },
      { name: 'mobileShow', isSelect: true },
      { name: 'type', isSelect: true },
    ])

  const props = defineProps({
    title: String, //新增/修改字段弹窗
    isOpen: Boolean,
    loading: Boolean, // 保存字段加载动画
    fieldVo: Object,
    type: {
      type: Number,
      default: 0,
    },
  })
  const { title, isOpen, loading, fieldVo, type } = toRefs(props)
  const emits = defineEmits(['on-save', 'on-close', 'on-delete'])
  // 字段对象
  const networkFieldVo = ref()
  watch(isOpen, (n) => {
    if (n) {
      networkFieldVo.value = _.cloneDeep(fieldVo!.value)
      
    }
  })
  // 表单元素
  const formRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入字段名称', trigger: ['blur', 'change'] }],
    val: [{ required: true, message: '请输入字段内容', trigger: ['blur', 'change'] }],
    required: [{ required: true, trigger: ['blur', 'change'] }],
    mobileShow: [{ required: true, message: '请选择是否前端显示', trigger: ['blur', 'change'] }],
    status: [{ required: true, message: '请选择字段状态', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '请选择字段类型', trigger: ['blur', 'change'] }],
    uploadSize: [
      { required: false, message: '请输入最大尺寸', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: ['blur', 'change'],
      },
    ],
    uploadQty: [
      { required: false, message: '请输入上传数量', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: ['blur', 'change'],
      },
    ],
  })
  const limitNum = (val, n) => {
    if (val > n) {
      val = n
    } else if (val == 0 && val != '') {
      val = 1
    }
    if (n == 100) {
      networkFieldVo.value.uploadSize = val
    } else {
      networkFieldVo.value.uploadQty = val
    }
  }

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    resetFormValidateResult()
    emits('on-close')
  }

  // 1-文本，2-多行文本，3-单选，4-多选，5-多图，6-附件，7-视频，8-评分
  const fieldOption0 = [
    { value: 1, name: '文本' },
    { value: 2, name: '多行文本' },
    { value: 3, name: '单选' },
    { value: 4, name: '多选' },
    { value: 5, name: '多图' },
    { value: 6, name: '附件' },
    { value: 7, name: '视频' },
    { value: 8, name: '评分' },
  ]

  // 1-文本，2-多行文本，3-单选，4-多选，5-多图，6-附件，7-视频
  const fieldOption1 = [
    { value: 1, name: '文本' },
    { value: 2, name: '多行文本' },
    { value: 3, name: '单选' },
    { value: 4, name: '多选' },
    { value: 5, name: '多图' },
    { value: 6, name: '附件' },
    { value: 7, name: '视频' },
  ]
  // 新增字段内容
  const addFieldContent = () => {
    networkFieldVo.value.contentVos.push({ id: '', val: '' })
  }

  // 删除字段内容
  const handleDele = (index, obj) => {
    networkFieldVo.value.contentVos.splice(index, 1)
    if (obj.id) {
      if (!networkFieldVo.value.delContentIds) {
        networkFieldVo.value.delContentIds = []
      }
      networkFieldVo.value.delContentIds.push(obj.id)
    }
  }

  // 修改弹窗的删除按钮
  const onDelNetworkField = (obj) => {
    ElMessageBox({
      type: 'warning',
      title: '温馨提示',
      icon: markRaw(Delete),
      message: `是否删除字段名称[ ${obj.name} ]? 删除后将不可恢复`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '删除中...'
          emits('on-delete', [obj.id])
          setTimeout(() => {
            done()
            instance.confirmButtonLoading = false
          }, 1000)
        } else {
          done()
        }
      },
    }).catch(() => {
      // 不可以删除这个注释，否则会报eslint的错误
    })
  }

  // 保存字段
  const saveData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        if (networkFieldVo.value.type === 3 || networkFieldVo.value.type === 4) {
          if (networkFieldVo.value.contentVos.length == 0) {
            ElMessage({
              message: '字段内容不能为空',
              type: 'warning',
              duration: 2000,
            })
            return
          }
          if (networkFieldVo.value.contentVos.filter((f) => f.val == '').length > 0) {
            ElMessage({
              message:
                networkFieldVo.value.type === 3 ? '单选字段内容不能为空' : '多选字段内容不能为空',
              type: 'warning',
              duration: 2000,
            })
            return
          }
          const tem: any = []
          for (let index in networkFieldVo.value.contentVos) {
            const con = networkFieldVo.value.contentVos[index]
            if (tem.indexOf(con.val) !== -1) {
              ElMessage({
                message: `第 ${Number(index) + 1} 行的字段内容[ ${con.val} ]已重复`,
                type: 'warning',
                duration: 2000,
              })
              return
            }
            tem.push(con.val)
          }
        }
        if (
          networkFieldVo.value.type === 5 ||
          networkFieldVo.value.type === 6 ||
          networkFieldVo.value.type === 7
        ) {
          if (networkFieldVo.value.uploadSize > 100) {
            ElMessage({
              message: `最大尺寸上限值 <= 100`,
              type: 'warning',
              duration: 2000,
            })
            return
          }
          if (networkFieldVo.value.uploadQty > 10) {
            ElMessage({
              message: `上传数量上限值 <= 10`,
              type: 'warning',
              duration: 2000,
            })
            return
          }
        }
        if (!(networkFieldVo.value.type === 3 || networkFieldVo.value.type === 4)) {
          networkFieldVo.value.contentVos = []
        }
        emits('on-save', networkFieldVo.value)
      }
    })
  }

  // 返回方法
  defineExpose({})
</script>

<style scoped lang="scss">
  .list {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-top: 12px;
    gap: 12px;
  }
</style>
